﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Meraz.Web.Models;
using Meraz.Web.Models.Twitter;
using Ninject;
using Meraz.Core.Managers;
using Meraz.Core.Model;
using Meraz.Core.Repositories;
using System.IO;
using Spark;
using Meraz.Web.Filters;
using System.Diagnostics;
using Meraz.Web.Views.Helpers;
using System.Net;
using Meraz.Core.Config;
using Meraz.Core.Parsers;
using System.Xml.Linq;

namespace Meraz.Web.Controllers
{
    public class TwitterController : BaseController
    {
    [Inject]
        public IOptionManager OptionManager { get; set; }
    [Inject]
    public DomainManager DomainManager { get; set; }
    [Inject]
    public TwitterManager TwitterManager { get; set; }

        //
        // GET: /Twitter/

    public ActionResult Index()
    {
        ViewData["Menu"] = Menu.Twitter;
        return View();
    }

        public ActionResult IndexOld()
        {
            ViewData["Menu"] = Menu.Twitter;

            StudyListModel<TwitterStudy> studyListModel = new StudyListModel<TwitterStudy>();
            studyListModel.Studies = TwitterManager.GetStudies();
            return View("Studies", studyListModel);

        }

        public ActionResult Domains()
        {
            ViewData["Menu"] = Menu.Twitter;
            TwitterDomainsModel model = new TwitterDomainsModel();
            model.Domains = DomainManager.All();
            return View(model);
        }

        public ActionResult Studies()
        {
            StudyListModel<TwitterStudy> studyListModel = new StudyListModel<TwitterStudy>();
            studyListModel.Studies = TwitterManager.GetStudies();
            return View("Studies", studyListModel);
        }

        public ActionResult Study(string studyID)
        {
            ViewData["Menu"] = Menu.Twitter;
            if (string.IsNullOrWhiteSpace(studyID))
            {
                //all studies
                StudyListModel<TwitterStudy> studyListModel = new StudyListModel<TwitterStudy>();
                studyListModel.Studies = TwitterManager.GetStudies();
                return View("Studies", studyListModel);
            }
            //one study
            TwitterStudyModel twitterStudyModel = new TwitterStudyModel();
            twitterStudyModel.Study = TwitterManager.GetStudy(int.Parse(studyID));
            List<string> studyUsers = twitterStudyModel.Study.TwitterUsers.Select(sel1 => sel1.Name).ToList();
            List<string> all = TwitterManager.GetTwitterUsers().Select(sel1 => sel1.Name).ToList();
            all.RemoveAll(rem => studyUsers.Contains(rem));
            twitterStudyModel.Usernames = all;
            return View("Study", twitterStudyModel);
        }

        [HttpPost]
        public ActionResult Study(string StudyID, string AddUserName)
        {
            ViewData["Menu"] = Menu.Twitter;

            int id;
            RowModel model = new RowModel();
            if (int.TryParse(StudyID, out id))
            {
                TwitterSection twitterSection =
                    (TwitterSection)ConfigHelper.GetSection("twitter");
                TwitterUser user = TwitterManager.AddUser(AddUserName, id, twitterSection);
                if (user != null)
                {
                    model.Values.Add(user.ID.ToString());
                    model.Values.Add(user.Name);
                    model.Values.Add(user.IsBlog.ToString().ToLower());
                    model.Values.Add(user.IsNewspaper.ToString().ToLower());
                    model.Values.Add(user.IsTopJournalist.ToString().ToLower());
                    model.Values.Add(user.IsTopPolitical.ToString().ToLower());
                    model.Message = "Success";
                }
            }
            if (string.IsNullOrEmpty(model.Message))
            {
                model.Message = "Fail";
            }

            TwitterStudyModel twitterStudyModel = new TwitterStudyModel();
            twitterStudyModel.Study = TwitterManager.GetStudy(int.Parse(StudyID));
            List<string> studyUsers = twitterStudyModel.Study.TwitterUsers.Select(sel1 => sel1.Name).ToList();
            List<string> all = TwitterManager.GetTwitterUsers().Select(sel1 => sel1.Name).ToList();
            all.RemoveAll(rem => studyUsers.Contains(rem));
            twitterStudyModel.Usernames = all;
            return View("Study", twitterStudyModel);
        }

        public ActionResult TwitterUsers()
        {
            ViewData["Menu"] = Menu.Twitter;
            if (Request.AcceptTypes.Contains("application/json"))
            {
                string[] users = TwitterManager.GetTwitterUsers().OrderBy(order1 => order1.Name).Select(select1 => select1.Name).ToArray();
                return Json(users, JsonRequestBehavior.AllowGet);
            }
            else
            {
                TwitterUsersModel model = new TwitterUsersModel();
                model.Users = TwitterManager.GetTwitterUsers();
                return View(model);
            }
        }

        public ActionResult TwitterUser(long id)
        {
            ViewData["Menu"] = Menu.Twitter;
            TwitterUser user = TwitterManager.GetTwitterUser(id);
            return View(user);
        }

        public ActionResult Tweets(string username)
        {
            ViewData["Menu"] = Menu.Twitter;
            TwitterUserModel model = new TwitterUserModel();
            try
            {
                model.TwitterUser = TwitterManager
                    .GetTweets(username);
            }catch(Exception ex){
                model.Message = ex.Message;
            }
            return View(model);
        }

        public ActionResult Tweet(string id)
        {
            long tweetID;
            if (!long.TryParse(id, out tweetID))
                tweetID = 0;
            TweetModel model = new TweetModel();
            try
            {
                model.Tweet = TwitterManager.GetTweet(tweetID);
                model.Genres = OptionManager.GetTwitterGenres(model.Tweet.Genre);
                model.Tones = OptionManager.GetTones(null);
                string html = RenderViewToHtml<TweetModel>("Twitter/_TweetDetails.spark", model);
                return Content(html);
            }
            catch (Exception problem)
            {
                string message = (problem is ApplicationException)? problem.Message 
                    : "There was a problem retrieving this record.";
                var response = HttpContext.Response;
                response.StatusCode = (int)HttpStatusCode.InternalServerError;
                response.AddHeader("MerazHeader", message);
                response.Write(message);
                response.End();
                return null;
            }
        }

        [ObjectFilter(Param = "tweet", RootType = typeof(Tweet))]
        [HttpPost]
        public ActionResult SaveTweet(Tweet tweet)
        {
            Tweet saved = TwitterManager.Save(tweet);
            RowModel model = new RowModel();
            model.Message = "Success";
            return Json(model);
        }


    }
}
